<?php

	function smuoi_upload_debug(){
		$ob = trim(ob_get_clean());
		if($ob) error_log($ob);
	}
	// register this before other funcs to prevent stats being reported in log
	smuoi_register_shutdown_function('smuoi_upload_debug');

	class Upload{
			
		var $tmpfil;
		var $filnam;
		var $dir;
		
		function __construct(){
			
			if(!$this->tmpfil = @$_FILES['Filedata']['tmp_name']) die('No uploaded file');
			if(!$this->filnam = @$_FILES['Filedata']['name']) die('No filename');
			
			$ustr = get('upload');
			
			$a = explode('@', $ustr);
			
			if(!$fmrp = array_pop($a)) die('fmrp is null'); 			
			if(!$token = array_pop(explode('/', array_shift($a)))) die('No token');
				
			$sesh = sn()->session()->auxiliary_data();
			$sesh->read();
			if(!is_array($a = $sesh->uploadtokens)) die('No uploads expected');
			
			$hash = md5($token . $this->filnam);
			$pass = false;
			foreach($a as $k=>$v){ 
				if($v !== $hash) continue;
				unset($a[$k]);
				$pass = true;
				break;
			}
			if(!$pass) die('Bad hash');
			$sesh->set('uploadtokens', $a);
			$sesh->write();
			
			if(!$this->dir = smrf($fmrp)) die("Object $fmrp could not be found");
			if(!$this->dir->is_writable()) die("Directory $fmrp not writeable");
		}
		
		function run(){
			$dstfil = HostInterface::filename_increment($this->dir->realpath($this->filnam));
			$new_tmpfile = dirname($this->tmpfil).'/'.$this->filnam;
			if(!move_uploaded_file($this->tmpfil, $new_tmpfile)) die('could not move');
			if(!$this->dir->appendChild($new_tmpfile)){
				unlink($new_tmpfile);
				die('could not append child');
			}
		}
		
	}

